from flask import Blueprint, request
from flask_restful import Resource, Api
from model.comment import Comment
from model.photo import Photo
from libs.response import generate_response
from model import db
from libs.auth import login
from libs.handler import default_error_handler

comment_bp = Blueprint("commentapi", __name__, url_prefix="/v1")
api = Api(comment_bp)


class CommentView(Resource):
    # 测试成功
    def post(self):
        photo_id = request.json.get("photo_id")
        comment_ip = request.json.get("comment_ip")
        comment_content = request.json.get("comment_content")
        # 判断评论的照片是否存在
        photo = Photo.query.filter_by(id=photo_id).first()
        if photo:
            comment_info = Comment(
                photo_id=photo_id,
                comment_ip=comment_ip,
                comment_content=comment_content
            )
            db.session.add(comment_info)
            db.session.commit()
            return generate_response(message="add comment success")
        else:
            return generate_response(status_code=10001, message="你评论的照片不存在！")

    # 测试成功
    def delete(self, id):
        result = Comment.query.get(id)
        if result is not None:
            db.session.delete(result)
            db.session.commit()
            return generate_response(message="delete comment success")
        else:
            return generate_response(status_code=10001, message="comment doesn't exist")

    # 测试成功
    def get(self, id=None):
        result_list = []
        if id is not None:
            comment = Comment.query.get(id)
            if comment is not None:
                comment.comment_time = str(comment.comment_time)
                result_list.append(comment)
                print(result_list)
                return generate_response(message="get comment success", data=[dict(i) for i in result_list])
            else:
                return generate_response(status_code=10001, message="comment doesn't exist")
        else:
            comments = Comment.query.all()
            for c in comments:
                c.comment_time = str(c.comment_time)
            result_list += comments
        return generate_response(message="get tags success", data=[dict(item) for item in result_list])


api.add_resource(CommentView, '/comment')
api.add_resource(CommentView, '/comment/<int:id>', endpoint="commentviewapi")